package com.atguigu.ggkt.exception;

import com.atguigu.ggkt.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/*
统一异常处理
 */
@ControllerAdvice //aop的方式切入，增强功能
public class GlobalExceptionHandler {

    //全局异常处理
    @ExceptionHandler(Exception.class)
    @ResponseBody //返回json格式的数据
    public Result error(Exception e){
        e.printStackTrace();
        return Result.fail().message("执行了全局异常处理！");
    }

    //特定异常处理
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result error(ArithmeticException e){
        e.printStackTrace();
        return Result.fail().message("执行了算术运算异常！");
    }

    //自定义异常
    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result error(CustomException e){
        e.printStackTrace();
        return Result.fail().code(e.getCode()).message(e.getMsg());
    }

    /*
try {
    int a = 10/0;
}catch(Exception e) {
    throw new CustomException(20001,"出现自定义异常");
}
     */
}
